# coding = utf-8

'''
Gabor 滤波
'''

import cv2,os
import numpy as np
import matplotlib.pyplot as plt
import SimpleITK as sitk
from PIL import Image

#构建Gabor滤波器
def build_filters():
    filters = []
    ksize = [7, 9, 11, 13, 15, 17]  # gabor尺度，6个
    #lamda = np.pi / 2.0  # 波长
    lamda  = 5
    for theta in np.arange(0, np.pi, np.pi / 4):  # gabor方向，0°，45°，90°，135°，共四个
        for K in range(6):
            kern = cv2.getGaborKernel((ksize[K], ksize[K]), 1.0, theta, lamda, 0.5, 0, ktype=cv2.CV_32F)
            kern /= 1.5 * kern.sum()
            filters.append(kern)
    print(len(filters))
    return filters

def build_filters_v2():
    filters = []
    ksize = [3,4,5,6,7,8]  # gabor尺度，6个
    #lamda = np.pi/2.0         # 波长
    lamda = [5,10,15,20,25,30]
    theta1 = [0, 1 * np.pi/4, 2*np.pi/4, 3*np.pi/4]
    theta2 = [0, 1 * np.pi/6, 2*np.pi/6, 3*np.pi/6, 4*np.pi/6, 5*np.pi/6]


    for z in lamda:
       #for t in theta1 :  # gabor方向，0°，45°，90°，135°，共四个
            kern = cv2.getGaborKernel((10, 10), sigma=1.0, theta=0, lambd=z, gamma=0.5, psi=0, ktype=cv2.CV_32F)
            kern /= 1.5 * kern.sum()
            filters.append(kern)

    print(len(filters))
    return filters


def filter_gabor(img):
    res = []  # 滤波结果
    filters = build_filters_v2()
    all = np.zeros_like(img)
    for i in range(len(filters)):
        # res1 = process(img, filters[i])
        accum = np.zeros_like(img)
        for kern in filters[i]:
            fimg = cv2.filter2D(img, cv2.CV_8UC1, kern)
            accum = np.maximum(accum, fimg, accum)
        res.append(np.asarray(accum))
        all += np.array(accum)

    '''
    for temp in range(len(res)):
        plt.subplot(2, 3, temp + 1)
        plt.imshow(res[temp], cmap='gray')
    plt.show()
    '''

    print(np.min(all), np.max(all))

    plt.subplot(1, 2, 1)
    plt.imshow(img, cmap="gray")
    plt.subplot(1, 2,2)
    plt.imshow(all, cmap="gray")
    plt.show()

    return res  # 返回滤波结果,结果为24幅图，按照gabor角度排列

def main():
    venous = "/datasets/qiye/DongBeiDaXue2/image_venous/data2_0628_venous.mha"
    artery = "/datasets/qiye/DongBeiDaXue2/image_arterial/data2_0628_arterial.mha"

    arterial_image = sitk.ReadImage(artery)
    arterial = sitk.GetArrayFromImage(arterial_image)

    venous_image = sitk.ReadImage(venous)
    venous = sitk.GetArrayFromImage(venous_image)

    arterial[arterial <= -250] = -250
    arterial[arterial > 250] = 250

    venous[venous <= -250] = -250
    venous[venous > 250] = 250

    arterial = arterial[140]
    venous = venous[140]

    venous = (venous + 250) / 500
    venous = venous * 255
    venous = venous.astype(np.uint8)

    res = filter_gabor(venous)
    venous = cv2.cvtColor(venous, cv2.COLOR_GRAY2BGR)
    return

    for i in range(len(res)):
         print(i)
         res_item = res[i]


         res_item = cv2.cvtColor(res_item, cv2.COLOR_GRAY2BGR)

         tumor_label_file = "E:\predict\image_tumor\case_00072\label_tumor\\140.png"
         tumor_label = Image.open(tumor_label_file).convert("L")
         tumor_label = np.array(tumor_label)
         label_copy = tumor_label.astype(np.uint8)
         contours, _ = cv2.findContours(label_copy, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
         for counter in contours:
                    data_list = []
         for t in range(counter.shape[0]):
            j = counter[t][0]
            data_list.append(j)
         cv2.polylines(venous, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)
         cv2.polylines(res_item, np.array([data_list], np.int32), True, [0, 255, 0], thickness=1)
         plt.subplot(1, 2, 1)
         plt.imshow(venous)
         plt.subplot(1, 2, 2)
         plt.imshow(res_item)
         plt.show()






if __name__ == '__main__':
    main()